package leetcode.hard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: $05_LongestPalindrome
 * Description: 最长回文子串
 * date: 2021-09-30 22:41
 *
 * @author liyifan
 */
public class $05_LongestPalindrome {
    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2)
            return s;

        String origin = s;
        String reverse = new StringBuffer(s).reverse().toString();
        int end = 0;
        int maxLen = 0;
        int[][] dp = new int[len][len];
        for (int i = 0;i < len;i++) {
            for (int j = 0;j < len;j++) {
                if (origin.charAt(i) == reverse.charAt(j)) {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    }
                }
                if (dp[i][j] > maxLen) {
                    int beforeRev = len - 1 - j;
                    if (beforeRev + dp[i][j] - 1 == i) { //判断下标是否对应
                        maxLen = dp[i][j];
                        end = i;
                    }
                }

            }
        }

        return s.substring(end - maxLen + 1, end + 1);
    }
}
